<template>
  <page-header-wrapper :title="false">
    <div>
      <a-row id="home_wrapper" type="flex">
        <a-col id="left_tree" flex="400px">
          <div>
            <a-tree checkable :show-line="true" :show-icon="false" :show-leaf-icon="false" :treeData="orgAllTreeData" :replaceFields="orgTreereplaceFields" @select="onSelectOrgTree">
            </a-tree>
          </div>
        </a-col>
        <div style="width:10px"></div>
        <a-col flex="auto">
          <div id="right-content-white">
            <a-card title="" :bordered="false">
            <div class="table-page-search-wrapper">
              <a-form layout="inline">
                <a-row :gutter="48">
                  <a-col :md="8" :sm="24">
                    <a-form-item label="护栏名称">
                      <a-input v-model="orgQueryParam.keyword" placeholder="" :allow-clear="true"/>
                    </a-form-item>
                  </a-col>

                  <a-col :md="8" :sm="24">
                    <span class="table-page-search-submitButtons" >
                      <a-button type="primary" @click="() => initQuery()">查询</a-button>
                      <!-- <a-button style="margin-left: 8px" @click="() => queryOrgParam = {}">重置</a-button> -->
                    </span>
                  </a-col>



                </a-row>
              </a-form>

              <div class="table-operator ">
                 <a-button type="primary" icon="plus" @click="() => handleAddOrg()">添加</a-button>
                <a-popconfirm
                      title="确认删除所选护栏？"
                      ok-text="确认"
                      cancel-text="取消"
                      @confirm="() => delOrg(orgSelectedRowKeys.join(','))"
                    >
                  <a-button v-if="orgSelectedRowKeys.length > 0" type="danger" icon="delete" >批量删除</a-button>
                </a-popconfirm>
              </div>

              <template>
                <a-table
                  size="small"
                  bordered
                  :columns="orgColumns"
                  :row-key="record => record.id"
                  :data-source="orgData"
                  :pagination="orgPagination"
                  :loading="loading"
                  @change="handleOrgTableChange"
                  :row-selection="{ selectedRowKeys: orgSelectedRowKeys, onChange: onOrgSelectChange }"
                >
                  <span slot="orgAction" slot-scope="text, record">
                    <a @click="() => handleEditOrg(record.id)"> <a-icon type="edit" /> 编辑 </a>
                    <!-- <a @click="() => handleEditOrg(record.id)"> <a-icon type="edit" /> 编辑 </a>
                    <a-divider type="vertical" /> -->
                    <a-popconfirm
                      title="确认删除该护栏？"
                      ok-text="确认"
                      cancel-text="取消"
                      @confirm="() => delOrg(record.id)"
                    >

                      <a href="#"> <a-icon type="delete" /> 删除</a>
                    </a-popconfirm>
                  </span>
                </a-table>
              </template>
            </div>
            </a-card>
          </div>
        </a-col>
      </a-row>
    </div>
    <a-modal
      class="rail-modal"
      :maskClosable="false"
      :title="orgOperType == 'add' ? '添加护栏' : '编辑护栏'"
      :width="800"
      :visible="!!orgOperType"
      :confirmLoading="loading"
      @ok="() => addOrEditOrg()"
      @cancel="() => cancelAddOrEditOrg()"
      :forceRender="true"
    >
      <a-spin :spinning="loading">
        <a-form ref="orgOperForm" :form="form" v-bind="formLayout">
          <a-row  :gutter="24" type="flex">
            <a-col :span="24" >
              <a-form-item v-show="false" label="主键ID" name="id">
                <a-input
                  type="hidden"
                  v-decorator="[
                    'id',
                    {
                      rules: [{ required: false }],
                    },
                  ]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12" >
              <a-form-item  label="所属项目" required name="projectId">
              <a-select :disabled="this.orgOperType !== 'add'?true:false"  placeholder="请选择项目" v-decorator="[
                    'projectId',
                    {
                      rules: [{ required: true, message: '请选择项目', validateTrigger: 'blur' }],
                    },
                  ]">
                <a-select-option v-for="item in projectList" :value="item.id">
                  {{item.name}}
                </a-select-option>
              </a-select>

            </a-form-item>
            </a-col>
            <a-col :span="12" >
          <a-form-item label="护栏名称" required name="name">
            <a-input
              v-decorator="[
                'name',
                {
                  rules: [
                    { required: true, message: '请输入护栏名称', whitespace: true, validateTrigger: 'blur' },
                    { max: 32, message: '单位名称长度不能超过32', trigger: 'blur' },
                  ],
                },
              ]"
            />
          </a-form-item>
            </a-col>
            <a-col :span="12" >
          <a-form-item label="护栏编码" required name="code">
            <a-input
              v-decorator="[
                'code',
                {
                  rules: [
                    { required: true, message: '请输入护栏编码', whitespace: true, validateTrigger: 'blur' },
                    { max: 32, message: '单位简称长度不能超过32', trigger: 'blur' },
                  ],
                },
              ]"
            />
          </a-form-item>
            </a-col>
            <a-col :span="12" >
          <a-form-item label="护栏地址"  name="address" >
            <a-input
              v-decorator="[
                'address',
                {
                  rules: [
                    { required: false, message: '请输入护栏地址', whitespace: true, validateTrigger: 'blur' },
                    { max: 255, message: '护栏地址长度不能超过255', trigger: 'blur' },
                  ],
                },
              ]"
            />
          </a-form-item>
            </a-col>
            <a-col :span="24" >
          <a-form-item label="备注"  name="bz">
            <a-textarea
              v-decorator="[
                'bz',
                {
                  rules: [
                    { required: false, message: '请输入备注', whitespace: true, validateTrigger: 'blur' },
                    { max: 255, message: '备注长度不能超过255', trigger: 'blur' },
                  ],
                },
              ]"
            />
          </a-form-item>
            </a-col>
            <a-col :span="24" >
          <a-form-item label="地图位置" required name="position">
            <div :class="positionFlag?'red-border':''" class="pop-position">
              <autoMap :isDraw="isDraw" :mapInfo="mapInfo" v-if="!!orgOperType" @getDrawPath="getDrawPath" ref="autoMap"></autoMap>
            </div>
          </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-modal>

  </page-header-wrapper>
</template>

<script>

import { TreeSelect } from 'ant-design-vue';
import {treeTransArray} from '@/utils/util'
import autoMap from "@/components/Map/autoMap";
import moment from "moment";

const orgColumns = [
  {
    title:'护栏名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '护栏编码',
    dataIndex: 'code',
    key: 'code',
  },
  {
    title: '所属单位',
    dataIndex: 'orgName',
    key: 'orgName',
  },
  {
    title: '所属项目',
    dataIndex: 'projectName',
    key: 'projectName',
  },
  {
    title: '安装地址',
    dataIndex: 'address',
    key: 'address',
  },
  {
    title: '设备数量',
    key: 'deviceCount',
    dataIndex: 'deviceCount'
  },
  {
    title: '操作',
    key: 'OrgAction',
    scopedSlots: { customRender: 'orgAction' },
  },
];
import tool from '@/utils/tool';
export default {
  name: 'RailList',
  components: {
      [TreeSelect.name]: TreeSelect,
      ATreeSelectNode: TreeSelect.TreeNode,
      autoMap
  },
  data() {
    return {
      form: this.$form.createForm(this),
      loading: false,
      position:'',//绘制路径
      positionUpdata:'',
      positionFlag:false,
      orgOperType:'',
      projectList:[],
      orgTreeSelect:{},
      orgAllTreeData: [],
      orgAllListData: [],
      orgAllData:[],
      orgTreereplaceFields: {
        title: 'lable',
        key:'id',
        value:'id'
      },
      formLayout : {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 }
      },
      orgColumns,
      orgSelectedRowKeys: [],
      orgQueryParam:{},
      orgPagination: {
        pageSize: 10,
        showQuickJumper: true,
        showTotal: (total, range) => `共 ${total} 条`,
      },
      orgData:[],
      mapInfo:[],//护栏地图落点的信息
      isDraw:true,//是否开启绘图
    }
  },
  mounted() {
    this.getOrgTree()
    this.getProject();
    this.queryOrgParam()
  },
  methods: {
    handleEditOrg(id) {
      this.orgOperType = 'edit'
      const operData = this.orgData.filter((i) => i.id == id)[0];
      this.isDraw=_.get(operData,'deviceCount')>0?false:true;//暂时在护栏上有设备的时候不让其编辑
      this.positionUpdata=operData.position;//保留更新时候没有修改路径值
      let tmp = {
        id: operData.id,
        name: operData.name,
        address: operData.address,
        code: operData.code,
        bz: operData.bz,
        position:operData.position,
        projectId:operData.projectId,
      }
      this.mapInfo=tool.fromatMapInfo([tmp]);
      this.form.setFieldsValue(tmp)
    },
    getDrawPath(data){//获取地图绘制的地理坐标
      this.position=this.formatPostion(data);
      this.positionFlag=false;
    },
    formatPostion(arr=[]) {
      let path=[];
      arr.map(item=>{
        path.push(item.lng+','+item.lat);
      })
      return JSON.stringify(path);
    },
    addOrEditOrg() {
      let validateFieldsKey = ['projectId', 'code', 'name', 'address', 'bz']
      // if (this.orgOperType === 'add') {
      //   validateFieldsKey.push(...['adminName', 'adminPhone', 'adminPwd', 'orgId'])
      // }
      //更新时候添加id
      if(this.orgOperType !== 'add'){
        validateFieldsKey.push('id');
      }
      this.form.validateFields(validateFieldsKey, (error, values) => {
        if (error) return

        let param = values
        //  处理地图
        if(this.position||this.orgOperType !== 'add'&&this.positionUpdata){
          param.position=this.position||this.positionUpdata;
        }else{
          this.positionFlag=true;
          return;
        }



        this.loading = true
        this.$http.post(this.orgOperType == 'add' ? '/sysRail/add' : '/sysRail/update', param).then((res) => {
          this.loading = false
          if (res.code == 0) {
            this.$notification['success']({
              message: '成功',
              description: `护栏${this.orgOperType == 'add' ? '添加' : '编辑'}成功`,
            })
            this.orgOperType = ''
            // this.getOrgTree()
            this.queryOrgParam()
          } else {
            this.$notification['error']({
              message: '错误',
              description: res.message,
              duration: 4,
            })
          }
        })
      })
    },
    async getProject(){
      let res = await this.$http.get('/sysProject/list');
      this.projectList=_.get(res,'data')||[];
    },
    handleAddOrg() {
      this.position='';//每次打开初始化路径
      this.isDraw=true;
      this.mapInfo=[];
      let preIsAdd = this.orgOperType == 'add'
      this.orgOperType = 'add'
      if (!preIsAdd) {
        // let tmp = {
        //   id: '',
        //   name: '',
        //   address: '',
        //   shortName: '',
        //   type: 'OEM',
        //   orgId: '',
        //   regdate: null,
        //   adminName: '',
        //   adminPhone: '',
        //   adminPwd: '',
        // }
        this.form.resetFields()
      }
    },
    cancelAddOrEditOrg() {
      this.orgOperType = ''

    },
    onSelectOrgTree(selectedKeys, info) {
      let selectOrgId = selectedKeys && selectedKeys.length > 0 ? selectedKeys[0] : '';
      if(!selectOrgId){
        this.orgTreeSelect = {};
      }else{
        //  判断选择的信息类型
        let item = this.orgAllListData.filter(i => i.id == selectOrgId)[0];
        if(item.type == 'ORG'){
          this.orgTreeSelect = {pOrgId:selectOrgId};
        }else if(item.type == 'PROJECT'){
          this.orgTreeSelect = {projectIds:selectOrgId};
        }
      }
      this.orgPagination.current = 1
      this.queryOrgParam();
    },
    getOrgTree() {
      this.$http.get('/web/common/getFullOrgTree').then((res) => {
        if(res.code == 0){
          this.orgAllListData = treeTransArray(JSON.parse(JSON.stringify(res.data)));
          this.orgAllTreeData = res.data
        }
      })
    },
    onOrgSelectChange(selectedRowKeys) {
      this.orgSelectedRowKeys = selectedRowKeys;
    },
    handleOrgTableChange(pagination, filters, sorter) {
      this.orgPagination.current = pagination.current;
      this.orgPagination.pageSize = pagination.pageSize;
      this.queryOrgParam(pagination.current,pagination.pageSize);
    },
    delOrg(id){
      this.loading = true;
      let param = {projectIds:id};
      this.$http.delete('/web/rail/delete',{params:param}).then((res) => {
        this.loading = false;
        if(res.code == 0){
          this.$notification['success']({
            message: '成功',
            description: '护栏已删除',
          })
          this.orgPagination.current = 1
          this.queryOrgParam();
        }else{
          this.$notification['error']({
            message: '错误',
            description: res.message,
            duration: 4,
          })
        }
      })
    },
    queryOrgParam(){
      this.loading = true;
      let param = Object.assign({},this.orgQueryParam);
      param = Object.assign(param,this.orgTreeSelect);
      param.start = this.orgPagination.current;
      param.limit = this.orgPagination.size;
      this.$http.get('/web/rail/page',{params:param}).then((res) => {
        this.loading = false;
        if(res.code == 0){
          let data = res.data;
          this.orgData = data.records;
          const pagination = { ...this.pagination };
          // Read total count from server
          // pagination.total = data.totalCount;
          pagination.total = data.total;
          pagination.current = data.current;
          pagination.pageSize = data.size;
          this.orgPagination = pagination;
        }
      })
   },
   initQuery(){
     this.orgPagination.current = 1;
     this.queryOrgParam();
   }
  },
}
</script>
<style scoped lang="less">
.pop-position{
  //height:420px;
}
.red-border{
  outline: 1px solid #ff0a00;
}
</style>